package com.yh.threadTest.test;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName Demo4
 * @Description TODO
 * @Author 0715-YuHao
 * @Date 2020/11/11 14:26
 */
public class Demo5 {

    public static void main(String[] args) {
        Runnable run = new Ticket();
        new Thread(run).start();
        new Thread(run).start();
        new Thread(run).start();
    }

    public static class Ticket implements Runnable {

        private int count = 10;

        //显示锁
        private Lock l = new ReentrantLock(true);

        @Override
        public void run() {
            while (true) {
                l.lock();
                if (count > 0) {
                    System.out.println(Thread.currentThread().getName() + ":正在卖票");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    count--;
                    System.out.println("卖票成功，余票：" + count);
                }else {
                    break;
                }
                l.unlock();
            }
        }
    }
}
